﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using System.Text;

namespace PeisongWeb.admin
{
    public partial class dynamicOrderEdit : adminPage
    {
        protected bool isUnderTransfer = false;

        protected int id
        {
            get
            {
                int tmp;
                try { tmp = Convert.ToInt32(ViewState["id"]); }
                catch { tmp = 0; }
                return tmp;
            }
            set
            { ViewState["id"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["orderid"] != null)
                {
                    if (Library.Number.IsIntPositive(Request.QueryString["orderid"]))
                    {
                        id = Convert.ToInt32(Request.QueryString["orderid"]);
                    }
                }

                if (id != 0)
                {
                    getDetails();
                    rptBind();
                }
                else
                {
                    //liAutoPercent.Visible = true;
                }

            }
        }
        private void getDetails()
        {
            OrderEntity order = logic.order.getByDynamicOrderId(id);
            txt_DynamicOrderId.Text = order.Orderid.ToString();
            txt_amount.Text = string.Format("{0:F2}", order.Amount);
            txt_status.Text = order.StatusName.ToString();
            txt_note.Text = order.Note.ToString();
            if (order.Status.ToString() == "1" || order.ReceiveDt.ToShortDateString() != DateTime.Now.AddDays(+1).ToString("yyyy-MM-dd"))
            {
                btn_Save.Visible = false;
            }
            isUnderTransfer = order.Status.ToString() == "6";

        }
        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            where.AppendFormat(" AND orderId={0}", id);
            DataSet ds = logic.order.selectDynamicOrderItem(where.ToString(), "inputDt", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {

            OrderEntity Dynamicorder = logic.order.getDynamicById(id);
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            where.AppendFormat(" AND orderId={0}", id);
            DataSet ds = logic.order.selectDynamicOrderItem(where.ToString(), "productId desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            DataTable dt = ds.Tables[1];
            int errorno = 0;
            decimal amount = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["nowprice"].ToString() != "")
                {

                    amount = amount + Convert.ToDecimal(Convert.ToDouble(dt.Rows[i]["nowprice"].ToString()) * Convert.ToDouble(dt.Rows[i]["quantity"].ToString()));
                }
                else
                {
                    errorno++;
                    logic.orderItem.updateDynamicOrderItem(Convert.ToInt32(dt.Rows[i]["orderId"].ToString()), Convert.ToInt32(dt.Rows[i]["productId"].ToString()), dt.Rows[i]["businessnature"].ToString());
                }
            }
            OrderEntity order = Dynamicorder;
            order.Amount = Math.Round(amount,2, MidpointRounding.AwayFromZero);
            order.StandardAmount = order.Amount;
            order.OrderNo = "";
            order.Status = "1";
            int OrderId = logic.order.insertWithDynamicOrder(order);
            string OrderNo = logic.order.getById(OrderId).OrderNo;
            int adminId = logic.sysAdmin.AdminID;
            logic.order.updateDynamicOrder(id, OrderNo, adminId);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["nowprice"].ToString() != "")
                {
                    OrderItemEntity oi = new OrderItemEntity();
                    oi = new OrderItemEntity();
                    oi.CustomerId = Convert.ToInt32(dt.Rows[i]["customerId"].ToString());
                    oi.SellerId = Convert.ToInt32(dt.Rows[i]["sellerId"].ToString());
                    oi.ProductId = Convert.ToInt32(dt.Rows[i]["productId"].ToString());
                    oi.Price = Convert.ToDecimal(dt.Rows[i]["nowprice"].ToString());
                    oi.SellerPrice = Convert.ToDecimal(dt.Rows[i]["sellerPrice"].ToString());
                    oi.Unit = dt.Rows[i]["unit"].ToString();
                    oi.Quantity = Convert.ToDecimal(dt.Rows[i]["quantity"].ToString());
                    oi.Note = dt.Rows[i]["note"].ToString();
                    oi.OrderId = OrderId;
                    oi.InitQuantity = oi.Quantity;
                    oi.BusinessNature = dt.Rows[i]["businessNature"].ToString();
                    logic.orderItem.insert(oi);
                }
            }
            Response.Redirect("DynamicOrderList.aspx");
        }

        protected void btn_Return_Click(object sender, EventArgs e)
        {
            Response.Redirect("DynamicOrderList.aspx");
        }
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int oiid = Convert.ToInt32(e.CommandArgument.ToString());
                logic.orderItem.deleteDynamicOrderItem(oiid);

                Library.Script.ClientMsg("删除成功.");
                getDetails();
                rptBind();
            }
            if (e.CommandName == "ReamrksEdit")
            {
                int oiid = Convert.ToInt32(e.CommandArgument.ToString());
                TextBox txtamount = (TextBox)e.Item.FindControl("txt_quantity");
                decimal quantity = Convert.ToDecimal(txtamount.Text.ToString());
                TextBox txtremarks = (TextBox)e.Item.FindControl("txtNote");
                string remarks = txtremarks.Text.ToString();
                logic.orderItem.updateDynamicOrderItemByOiid(oiid, remarks, quantity);
                getDetails();
                rptBind();
            }
        }
    }
}
